import MyModal from "@/components/MyModal";
import { addFacility, editFacility, getFacilityDetail } from "@/services/facility/facility";
import { useBoolean, useRequest } from "ahooks";
import { Form, Input, InputNumber, message } from "antd";
import { useMemo } from "react";

export default ({ open, close, refresh, id }) => {
  const [form] = Form.useForm();
  const [loading, { toggle: toggleLoading }] = useBoolean(false);
  const onOk = async () => {
    const values = await form.validateFields();
    const fun = id ? editFacility : addFacility;
    toggleLoading();
    try {
      await fun({ ...values, facilityId: id });
      message.success(id ? "修改成功" : "新增成功");
      close();
      refresh();
    } finally {
      toggleLoading();
    }
  };
  const { loading: queryLoading } = useRequest(getFacilityDetail, {
    manual: !id,
    defaultParams: [id],
    onSuccess: (res) => {
      form.setFieldsValue(res);
    },
  });

  const title = useMemo(() => {
    return (id ? "修改" : "新增") + "设施信息";
  }, [id]);
  return (
    <MyModal
      title={title}
      open={open}
      close={close}
      onOk={onOk}
      queryLoading={queryLoading}
      confirmLoading={loading}
    >
      <Form form={form} wrapperCol={{ span: 24 }} layout="vertical">
        <Form.Item
          name="facilityName"
          rules={[
            {
              required: true,
            },
          ]}
          label="名称"
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="facilityPrice"
          label="价格"
          rules={[
            {
              required: true,
            },
          ]}
        >
          <InputNumber min={1} addonAfter="元" />
        </Form.Item>
      </Form>
    </MyModal>
  );
};
